package com.example.demoamqp.config;

import com.example.demoamqp.conatants.Constants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMqConfig {

    /**
     *  普通交换机
     * @return
     */
    @Bean
    public DirectExchange normalExchange(){
        return new DirectExchange(Constants.MQ_NORMAL_EXCHANGE,
                Constants.durable,
                Constants.autoDelete);
    }

    /**
     * 普通队列
     * @return
     */
    @Bean
    public Queue normalQueue(){
        Map<String, Object> map = new HashMap<>(2);
        map.put("x-dead-letter-exchange",Constants.MQ_DELAY_EXCHANGE);
        map.put("x-dead-letter-routing-key",Constants.MQ_DELAY_ROUTING_KEY);
        return new Queue(
                Constants.MQ_NORMAL_QUEUE,
                Constants.durable,
                Constants.exclusive,
                Constants.autoDelete,
                map);
    }

    /**
     * 绑定普通交换机
     * @return
     */
    @Bean
    public Binding normalBinding(){
        return BindingBuilder.bind(normalQueue())
                .to(normalExchange())
                .with(Constants.MQ_NORMAL_ROUTING_KEY);
    }


    //------------------死信队列设计--------------------------
    /**
     * 死信(延迟)队列
     * @return
     */
    @Bean
    public Queue delayQueue(){
        return new Queue(Constants.MQ_DELAY_QUEUE,
                Constants.durable,
                Constants.exclusive,
                Constants.autoDelete);
    }
    /**
     * 死信交换机
     * @return
     */
    @Bean
    public DirectExchange delayExchange(){
        return new DirectExchange(Constants.MQ_DELAY_EXCHANGE,
                Constants.durable,
                Constants.autoDelete);
    }
    /**
     * 死信交换机队列绑定
     * @return
     */
    @Bean
    public Binding delayBinding(){
        return BindingBuilder.bind(delayQueue())
                .to(delayExchange())
                .with(Constants.MQ_DELAY_ROUTING_KEY);
    }
}
